import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import router from '../router/index'
export class Request {
    public static axiosInstance: AxiosInstance;
    public static init() {
        this.axiosInstance = axios.create({
            baseURL: '/api',
            timeout: 6000
        })
        this.initInterceptors();
        return axios
    }
    public static initInterceptors() {
        this.axiosInstance.defaults.headers.post['Content-type'] = "application/x-www-form-urlencoded"
        this.axiosInstance.interceptors.request.use(
            (config: AxiosRequestConfig) => {
                const token = localStorage.getItem("ACCESS_TOKEN");
                if (token) {
                    // config.headers.Authorization = token
                    console.log(token)
                }
                return config;
            },
            (error: any) => {
                console.log(error)

            }
        )
        this.axiosInstance.interceptors.response.use(
            (response: AxiosResponse) => {
                if (response.data.code == '000000') {
                    return response
                } else {
                    Request.errorHandle(response)
                    return response
                }
            },
            (error: any) => {
                const { response } = error
                if (response) {
                    Request.errorHandle(response)
                    return Promise.reject(response.data)
                } else {
                    console.log(error)
                }
            }
        )
    }
    public static errorHandle(res: any) {
        switch (res.status) {
            case 401:
                router.push('/404')
                break;
            case 403:
                router.push('/404')
                break;
            case 404:
                router.push('/404')
                break;
            default:
                router.push('/500')
                console.log("连接错误")
        }

    }
}